<?php
namespace app\admin\controller;

use app\admin\model\Node;
use app\admin\model\NodeModel;
use app\admin\model\RoleModel;
use app\admin\model\UserType;
use app\admin\model\DepartmentModel;
use think\Db;

class Role extends Base
{
    // 角色列表
    public function index()
    {
        if(request()->isAjax()){

            $param = input('param.');

            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = [];
            if (!empty($param['searchText'])) {
                $where['role_name'] = ['like', '%' . $param['searchText'] . '%'];
            }

            $user = new RoleModel();
            $selectResult = $user->getRoleByWhere($where, $offset, $limit);

            foreach($selectResult as $key=>$vo){
                $selectResult[$key]['department'] = DB::name('department')->where('id',$vo['department_id'])->value('name');
                // 不允许操作超级管理员
                if(1 == $vo['id']){
                    $selectResult[$key]['operate'] = '';
                    continue;
                }
            }
			return [
				'code' => 1,
				'msg' => '加载成功',
				'data' => [
					'rows' => $selectResult,
					'total' =>  $user->getAllRole($where)
				]
			];
        }
		$authGroup = DB::name("auth_group")->order("id asc")->select();
		$this->assign([
			'authGroup' => $authGroup
		]);
        return $this->fetch();
    }

    // 添加角色
    public function roleAdd(){
        if(request()->isPost()){
            $param = input('post.');
            $role = new RoleModel();
            $flag = $role->insertRole($param);
			// 重新写入所有角色的可视权限
			$allRoles = DB::name('role')->where('id','<>',1)->where('department_id','<>',0)->select();
			foreach($allRoles as $k => $v){
				$this->autoGiveSee($v['can_see_type'],$v['id']);
			}
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
        return $this->fetch();
    }

    // 编辑角色
    public function roleEdit(){
        $role = new RoleModel();
        if(request()->isPost()){
            $param = input('post.');
            $flag = $role->editRole($param);
			// 重新写入所有角色的可视权限
			$allRoles = DB::name('role')->where('id','<>',1)->where('department_id','<>',0)->select();
			foreach($allRoles as $k => $v){
				$this->autoGiveSee($v['can_see_type'],$v['id']);
			}
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
        $id = input('param.id');
        $this->assign([
            'role' => $role->getOneRole($id)
        ]);
        return $this->fetch();
    }

    // 删除角色
    public function roleDel()
    {
        $id = input('param.id');
		// 重新写入所有角色的可视权限
		$allRoles = DB::name('role')->where('id','<>',1)->where('department_id','<>',0)->select();
		foreach($allRoles as $k => $v){
			$this->autoGiveSee($v['can_see_type'],$v['id']);
		}
        $role = new RoleModel();
        $flag = $role->delRole($id);
        return json(msg($flag['code'], $flag['data'], $flag['msg']));
    }

	public function isHaveSon($node_id) {
		$count = DB::name("node")->where('type_id',$node_id)->count();
		if($count == 0){
			return false;
		}else{
			return true;
		}
	}

    /**
     * [分配操作权限]
     */
    public function giveAccess()
    {
        $param = input('param.');
        $node = new NodeModel();
        // 获取现在的权限
        if('get' == $param['type']){
            $arr = $node->getNodeInfo($param['id']);
			$arr['node'] = $this->arr2tree($arr['node'],'id','pid','children');
			if(!empty($arr['rule'])){
				foreach($arr['rule'] as $k => $v){
					if($this->isHaveSon($v)){
						unset($arr['rule'][$k]);
					}
				}
			}
            return ['code'=>1,'msg'=>'加载成功','data'=>$arr];
        }

        // 分配新权限
        if('give' == $param['type']){
			if(!isset($param['rule'])){
				$param['rule'][] = 0;
			}
            $doparam = [
                'id' => $param['id'],
                'rule' => implode(",",$param['rule'])
            ];
            $user = new RoleModel();
            $flag = $user->editAccess($doparam);
            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }
    }

    /**
     * [分配可视权限]
     */
    public function giveSee(){
		$type = input('post.type');
        $role_id = input('post.role_id');
        if($type == ''){
            return ['code'=>0,'msg'=>'请选择'];
        }
        $role = new RoleModel();
        $depart_id = $role->getOneRole($role_id)['department_id'];
        $user_ids = $role->getUsersByDepartId($depart_id);
        $user_ids_str = implode(",",$user_ids);

        $depart = new DepartmentModel();
        $departs_ids = $depart->getSonsByPid($depart_id);
        foreach ($departs_ids as $k => $v) {
            $departs_ids[$k] = $v['id'];
        }
        array_push($departs_ids,$depart_id);
        foreach($departs_ids as $k => $v){
            $all_user_ids[$k] = $role->getUsersByDepartId($v);
        }
        $all_user_ids = array_reduce($all_user_ids,function($result,$value){
                    return array_unique(array_merge($result, array_values($value)));
                }, array());
        $all_user_ids_str = implode(",",$all_user_ids);

        $param['id'] = $role_id;
        $param['can_see_type'] = $type;
        switch ($type) {
            case '0'://仅自己
                $param['can_see'] = '-1';
                break;
            case '1'://所属部门
                $param['can_see'] = $user_ids_str;
                break;
            case '2'://所属部门和下级所有部门
                $param['can_see'] = $all_user_ids_str;
                break;
            case '3'://所有部门
                $param['can_see'] = '*';
                break;
            default://默认仅自己
                $param['can_see'] = '-1';
                break;
        }
        return $role->editCansee($param);
    }

    public function getCanseeType(){
        $id = input('id');
        return DB::name('role')->where('id',$id)->value('can_see_type');
    }

	/**
     * [分配可视权限]
     */
    public function autoGiveSee($type,$role_id){
        if($type == ''){
            return ['code'=>0,'msg'=>'请选择'];
        }
        $role = new RoleModel();
        $depart_id = $role->getOneRole($role_id)['department_id'];
        $user_ids = $role->getUsersByDepartId($depart_id);
        $user_ids_str = implode(",",$user_ids);

        $depart = new DepartmentModel();
        $departs_ids = $depart->getSonsByPid($depart_id);
        foreach ($departs_ids as $k => $v) {
            $departs_ids[$k] = $v['id'];
        }
        array_push($departs_ids,$depart_id);
        foreach($departs_ids as $k => $v){
            $all_user_ids[$k] = $role->getUsersByDepartId($v);
        }
        $all_user_ids = array_reduce($all_user_ids,function($result,$value){
                    return array_unique(array_merge($result, array_values($value)));
                }, array());
        $all_user_ids_str = implode(",",$all_user_ids);

        $param['id'] = $role_id;
        $param['can_see_type'] = $type;
        switch ($type) {
            case '0'://仅自己
                $param['can_see'] = '-1';
                break;
            case '1'://所属部门
                $param['can_see'] = $user_ids_str;
                break;
            case '2'://所属部门和下级所有部门
                $param['can_see'] = $all_user_ids_str;
                break;
            case '3'://所有部门
                $param['can_see'] = '*';
                break;
            default://默认仅自己
                $param['can_see'] = '-1';
                break;
        }
        return $role->editCansee($param);
    }

	public function authGroup() {
		if($this->request->isPost()){
			$data['rows'] = DB::name('auth_group')->order("id desc")->select();
			return [
				'code' => 1,
				'msg' => '加载成功',
				'data' => $data
			];
		}
		return $this->fetch();
	}

	public function authGroupAdd() {
		$param = input("post.");
		if($param['name'] == ''){
			return ['code'=>0,'msg'=>'名称不能为空'];
		}else{
			$name = trim($param['name']);
		}
		$count = DB::name('auth_group')->where("name",$name)->count();
		$data = [
			'name' => $name,
			'node_ids' => implode(",",$param['rule'])
		];
		DB::startTrans();
		try {
			if($count != 0){
				DB::name('auth_group')->where("name",$name)->update($data);
				$msg = "编辑";
			}else{
				DB::name('auth_group')->insert($data);
				$msg = "添加";
			}
			DB::commit();
			return ['code'=>1,'msg'=>$msg.'成功'];
		} catch (\Exception $e) {
			DB::rollback();
			return ['code'=>0,'msg'=>$msg.'失败:'.$e->getMessage()];
		}
	}

	public function authGroupdel() {
		$param = input("post.");
		DB::startTrans();
		try {
			DB::name('auth_group')->where('id',$param['id'])->delete();
			DB::commit();
			return ['code'=>1,'msg'=>'删除成功'];
		} catch (\Exception $e) {
			DB::rollback();
			return ['code'=>0,'msg'=>'删除失败:'.$e->getMessage()];
		}
	}

	public function getNodeRules() {
		$param = input('param.');
        $node = new NodeModel();
		$arr = $node->getAuthGroupNodeInfo($param['id']);
		$arr['node'] = $this->arr2tree($arr['node'],'id','pid','children');
		if(!empty($arr['rule'])){
			foreach($arr['rule'] as $k => $v){
				if($this->isHaveSon($v)){
					unset($arr['rule'][$k]);
				}
			}
		}
		return ['code'=>1,'msg'=>'加载成功','data'=>$arr];
	}

	public function giveAccessGruop(){
        $param = input('post.');
        // 分配新权限
		$gruop = DB::name('auth_group')->where("id",$param['group_id'])->find();
		$doparam = [
			'id' => $param['role_id'],
			'rule' => $gruop['node_ids']
		];
		DB::name("role")->where("id",$param['role_id'])->update([
			'auth_gruop_name' => $gruop['name']
		]);
		$user = new RoleModel();
		$flag = $user->editAccess($doparam);
		return json(msg($flag['code'], $flag['data'], $flag['msg']));
    }
}
